import React from 'react';
import { Form, Drawer, Input, Tree, Button, message, Spin, Table, Select, DatePicker } from 'antd';
import { connect } from 'dva';

const { TreeNode } = Tree;

class TradeAdd extends React.Component {
	state = {
		accountData: [],
		visible: false,
		row: null,
		menuTree: [],
		checkedKeys: [],
		loading: true,
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		}
	}

	initData = (row) => {
		if (row) {
			this.getMenus(row);
		} else {
			this.getMenusByAdmin();
		};
		this.setState({
			visible: true,
			row: row,
			loading: row ? true : false,
		})
	}

	setData = data => {
		this.props.form.setFieldsValue({
			name: data.name,
			username: data.username,
		});
		this.setState({ loading: false });
	}

	getMenusByAdmin = () => {
		const { dispatch } = this.props;
		dispatch({
			type: 'tenantManagement/getMenuTreeByAdmin',
			payload: { id: 0 },
			callback: res => {
				this.setState({ menuTree: res ? res : [] }, () => {
					this.getSelectMenu(res ? res : []);
				})
			},
		});
	}

	getMenus = row => {
		const { dispatch } = this.props;
		dispatch({
			type: 'tenantManagement/getMenuTree',
			payload: { id: row.id },
			callback: res => {
				this.setState({ menuTree: res.tree ? res.tree : [] }, () => {
					this.getSelectMenu(res.tree);
					this.setData(res);
				})
			},
		});
	}

	onCheck = (checkedKeys, info) => {
		this.setState({ checkedKeys });
	};

	onClose = () => {
		this.props.form.resetFields();
		this.setState({
			visible: false,
			accountData: [],
			row: null,
			checkedKeys: [],
			loading: true,
		})
	}

	onSubmit = () => {
		const { accountData, row, checkedKeys } = this.state;
		this.props.form.validateFields((errors, values) => {
			if (!errors) {
				if (!checkedKeys || checkedKeys.length === 0) {
					return message.error('请选择功能权限');
				};
				if (row) {
					this.editTenant(values);
				} else {
					this.addTenant(values);
				}
			}
		})
	}

	editTenant = data => {
		const { dispatch } = this.props;
		const { checkedKeys, row } = this.state;
		data.menus = checkedKeys;
		data.id = row.id;
		dispatch({
			type: 'tenantManagement/editTenant',
			payload: data,
			callback: res => {
				// message.info(res.message);
				this.onClose();
				this.props.getList();
			},
		});
	}

	addTenant = data => {
		const { dispatch } = this.props;
		const { checkedKeys } = this.state;
		data.menus = checkedKeys;
		dispatch({
			type: 'tenantManagement/addTenant',
			payload: data,
			callback: res => {
				if (res.code === 0) {
					message.info(res.message);
					this.onClose();
					this.props.getList();
				}
			},
		});
	}

	checkFieldForPassword(rule, value, callback) {
		const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
		if (rule.field === 'password') {
			if (value) {
				if (reg.test(value)) {
					if (value.length > 30 || value.length < 6) {
						callback('只可填入8-20位数字和字母组合');
					} else {
						callback();
					}
				} else {
					callback('只可填入8-20位数字和字母组合');
				}
			} else {
				callback('只可填入8-20位数字和字母组合');
			}
		}
	}

	renderTreeNode = data => {
		return data.map(item => {
			if (item.children) {
				return (
					<TreeNode title={item.name} key={item.id}>
						{this.renderTreeNode(item.children)}
					</TreeNode>
				)
			};
			return <TreeNode title={item.name} key={item.id} />;
		})
	}

	getSelectMenu = data => {
		const that = this;
		let { checkedKeys } = that.state;
		data.map(item => {
			if (item.children && item.children.length > 0) {
				const childrenChecked = item.children.filter(child => child.checked);
				if (childrenChecked.length === item.children.length) {
					checkedKeys.push(item.id);
				};
				that.getSelectMenu(item.children);
			} else {
				if (item.checked) {
					checkedKeys.push(item.id);
				}
			}
		});
		that.setState({ checkedKeys });
	}

	checkField(rule, value, callback) {
		const reg = /^[0-9a-zA-Z_.@]{1,}$/g;
		if (rule.field === 'username') {
			if (value) {
				if (reg.test(value)) {
					if (value.length > 30 || value.length < 6) {
						callback('支持6-30位大小写字母、数字、下划线、小数点、和@符号');
					} else {
						callback();
					}
				} else {
					callback('支持6-30位大小写字母、数字、下划线、小数点、和@符号');
				}
			} else {
				callback('支持6-30位大小写字母、数字、下划线、小数点、和@符号');
			}
		}
	}

	render() {
		const { title } = this.props;
		const { getFieldDecorator } = this.props.form;
		const { visible, menuTree, row, checkedKeys, loading } = this.state
		const formItemLayout = {
			labelCol: { span: 4 },
			wrapperCol: { span: 20 },
		};

		return (
			<Drawer
				title={title}
				visible={visible}
				closable
				width={600}
				onClose={this.onClose}
				destroyOnClose
			>
				<Spin spinning={loading}>
					<Form {...formItemLayout}>
						<Form.Item label="企业名称">
							{getFieldDecorator('tradeName', {
								rules: [
									{ required: true, message: '企业名称必填' }
								],
								getValueFromEvent: event => event.target.value.replace(/\s+/g, '')
							})(
								<Input placeholder="请输入" maxLength={60} autoComplete="off" />
							)}
						</Form.Item>
						<Form.Item label="管理员账号">
							<Table
								bordered
								columns={[
									{
										title: '管理员名称',
										dataIndex: "adminName",
										key: "adminName",
									},
									{
										title: '管理员账号',
										dataIndex: "adminAccount",
										key: "adminAccount",
									},
									{
										title: '手机号码',
										dataIndex: "phone",
										key: "phone",
									},
									{
										title: '操作',
										render: (_, row) => {
											return <span>
												<Button type="link">编辑</Button>
												<Button type="link">重置密码</Button>
												<Button type="link">删除</Button>
											</span>
										}
									}
								]}
								pagination={false}
							/>
							<Button type="primary">添加</Button>
						</Form.Item>
						<Form.Item label="是否审查">
							{getFieldDecorator('whetherToReview', {
								rules: [
									{ required: true, message: '请选择是否审查' }
								]
							})(
								<Select>
									<Select.Option value="approv">已通过</Select.Option>
									<Select.Option value="fail">未通过</Select.Option>
									<Select.Option value="uncensor">未审查</Select.Option>
								</Select>
							)}
						</Form.Item>
						<Form.Item label="有效期">
							{getFieldDecorator('periodValidity', {
								rules: [
									{ required: true, message: '请选择有效期' }
								]
							})(<DatePicker />)}
						</Form.Item>
						<Form.Item label={'功能权限'}>
							{getFieldDecorator('menus')(
								<Tree
									checkable
									checkedKeys={checkedKeys}
									onCheck={this.onCheck}
									style={{ width: '100%', height: '200px', overflowY: 'auto', marginTop: 16 }}
									dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
								>
									{this.renderTreeNode(menuTree)}
								</Tree>
							)}
						</Form.Item>
						<Form.Item label="有效期">
							{getFieldDecorator('remarks')(
								<Input.TextArea placeholder="请输入" rows={4} />
							)}
						</Form.Item>
					</Form>
				</Spin>
				<div
					style={{
						position: 'absolute',
						right: 0,
						bottom: 0,
						width: '100%',
						borderTop: '1px solid #e9e9e9',
						padding: '10px 16px',
						background: '#fff',
						textAlign: 'right',
					}}
				>
					<Button onClick={this.onClose} style={{ marginRight: 8 }}>
						取消
					</Button>
					<Button onClick={this.onSubmit} type="primary">
						确定
					</Button>
				</div>
			</Drawer>
		)
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(TradeAdd));
